const JWT = require("jwt-simple") ,
    AppError = require("../AppError")

const tokenName = "__token"

class RequestAuth {

    constructor( secret ){
        this.secret = secret 
        this.authConfigs = {}
    }

    static setPayloadFactory( group , factory ){
        if( !this.payloadFactory ){
            this.payloadFactory[ group ] = factory
        }
    }

    token(  payload ){
        return JWT.encode( payload , this.secret )
    }

    tokenName(){
        return tokenName
    }

    data( token ){
        try{
            return JWT.decode( token , this.secret )
        }catch(er){
            throw new AppError( 60 , "非法授权" )
        }
    }

    setAuthConfig( uri , config ){
        this.authConfigs[ uri ] = config 
    }

    getAuthConfig( uri ){
        return this.authConfigs[ uri ]
    }

}

class AuthConfig {

    constructor( opt  ){
        this.group = opt.group || "default" //项目分组标识
        this.id = opt.id || "normal"        //默认通用权限,其他为代号
        this.name = opt.name ,
        this.from = opt.from || "cookie"    //header.__token   cookie.__token
    }

    static to(  group , from , name , id ){
        return new AuthConfig({
            name : name ,
            id : id , 
            group : group ,
            from : from 
        })
    }

    static header(){
        return "header"
    }

    static cookie(){
        return "cookie"
    }

    getToken( ctx ){
        if( this.from == "cookie" ){
            return ctx.cookies.get( tokenName ) || null 
        }else if( this.from == "header"){
            return ctx.request.headers[ tokenName ]|| null 
        }
        return null 
    }

    isGroup( group ){
        return group == this.group 
    }

}

module.exports = {
    RequestAuth , AuthConfig 
} 